package com.ylp.sys.auth.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ylp.common.constants.HttpStatus;
import com.ylp.common.exception.ServiceException;
import com.ylp.common.response.Result;
import com.ylp.common.utils.StringUtils;
import com.ylp.sys.auth.config.cache.CurrentHashMapManager;
import com.ylp.sys.auth.entity.LoginDto;
import com.ylp.sys.auth.entity.LoginVo;
import com.ylp.sys.auth.entity.UserInfo;
import com.ylp.sys.auth.service.AuthService;
import com.ylp.sys.auth.utils.BCryptUtils;
import com.ylp.sys.auth.utils.ValidataCodeUtil;
import com.ylp.sys.domain.entity.*;
import com.ylp.sys.mapper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AuthServiceImpl implements AuthService {
    private static final Logger log = LoggerFactory.getLogger(AuthServiceImpl.class);
    private final SysUserMapper userMapper;
    private final CurrentHashMapManager currentHashMapManager;

    public AuthServiceImpl(SysUserMapper sysUserMapper, CurrentHashMapManager currentHashMapManager) {
        this.userMapper = sysUserMapper;
        this.currentHashMapManager = currentHashMapManager;
    }

    @Override
    public LoginVo login(LoginDto loginDto) {
        SysUser user = getUserByName(loginDto.getUsername());
        if (ObjectUtil.isNull(user)) {
            throw new ServiceException(HttpStatus.UNAUTHORIZED,"认证失败！");
        }
        if (!BCryptUtils.checkpw(loginDto.getPassword(), user.getPassword())) {
            throw new ServiceException(HttpStatus.UNAUTHORIZED,"密码错误！");
        }
        LoginVo loginVo = null;
        try {
            loginVo= getLoginVo(user);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(HttpStatus.UNAUTHORIZED, "用户相关信息错误");
        }
        // 登录，获取tokenInfo , 存储用户session
        if (loginDto.getRememberMe()) {
            StpUtil.login(user.getId());    // 登录
        } else {
            StpUtil.login(user.getId(), false);    // 登录
        }

        // 设置用户信息
        StpUtil.getSession().set("userInfo", new UserInfo(user.getId(), user.getUsername()));
        // 获取token
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        loginVo.setSaTokenInfo(tokenInfo);
        return loginVo;
    }

    /**
     * 根据账号查用户
     * @param userName
     * @return
     */
    public SysUser getUserByName(String userName) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotEmpty(userName), SysUser::getUsername, userName);
        wrapper.eq(SysUser::getStatus, 0);
        return userMapper.selectOne(wrapper);
    }

    private LoginVo getLoginVo(SysUser user) {
        LoginVo loginVo = new LoginVo();
        loginVo.setUserInfo(user);
        // 查询角色标识
        List<String> roleLabelList = getRoleLabelListByUserId(user.getId());
        loginVo.setRoleLabelList(roleLabelList);
        // 权限列表
        List<String> permissionList = getPermissionListByUserId(user.getId());
        loginVo.setPermissionList(permissionList);
        return loginVo;
    }

    /**
     * 获取验证码
     */
    @Override
    public String getCode(String ip) {
        ValidataCodeUtil.Validate validate = ValidataCodeUtil.getRandomCode();
        // 缓存验证码
        currentHashMapManager.put(ip, validate.getValue());
        System.out.println(validate.getValue());
        System.out.println(validate.getValue());
        System.out.println(validate.getValue());
        return validate.getBase64Str();
    }

    /**
     * 验证验证码
     *
     * @param code
     * @return
     */
    @Override
    public Result<String> checkCode(String code, String ip) {
        //取出内存中的验证码与传递过来的验证码比对，如果相同，返回true
        String cacheCode = (String) currentHashMapManager.get(ip);
        if (code.equalsIgnoreCase(cacheCode)) {
            // y验证成功 删除缓存
            currentHashMapManager.remove(ip);
            return Result.success("success", null);
        }
        return Result.success("failed", null);
    }







    /**
     * 根据用户id查询权限列表
     * @param userId
     * @return
     */
    public List<String> getPermissionListByUserId(Long userId) {
        List<String> perms = new ArrayList<>();
        try {
            perms = userMapper.selectPermsByUserId(userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return perms;
    }


    /**
     * 根据用户id查角色标识列表
     * @param userId
     * @return
     */
    public List<String> getRoleLabelListByUserId(Long userId) {
        List<String> roleLabelList = new ArrayList<>();
        try {
           roleLabelList = userMapper.selectRoleLabelByUserId(userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return roleLabelList;
    }

}
